package com.un.core.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.un.core.common.Constants;
import com.un.core.exception.ServiceException;
import com.un.web.sys.domain.entity.SysUser;
import com.un.web.sys.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author xingjian
 * @Date 2023-01-29
 **/
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        if (token.equals("authorizer=wuyunjian")){
            return true;
        }
        if(StrUtil.isEmptyIfStr(token)){
            throw new ServiceException(Constants.CODE_401,"无token，请重新登录");
        }
        String userId;
        try{
            userId = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j){
            throw new ServiceException(Constants.CODE_401,"token验证失败");
        }

        SysUser sysUser = userService.selectByPrimaryKey(Integer.valueOf(userId));
        if(sysUser == null){
            throw new ServiceException(Constants.CODE_401,"用户不存在，请重新登录");
        }
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(sysUser.getPassword())).build();
        try{
            jwtVerifier.verify(token);
        }catch (JWTVerificationException j){
            throw new ServiceException(Constants.CODE_401,"token验证失败，请重新登录");
        }
        return true;
    }
}
